﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Collections;

namespace ZT.Core.Utility
{
    /// <summary>
    /// 独立方法类
    /// </summary>
    public static class Command
    {

        /// <summary>
        /// 获取枚举项集合
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static IEnumerable<EnumItem> GetItems(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new InvalidOperationException();

            IList<EnumItem> list = new List<EnumItem>();

            // 获取Description特性 
            Type typeDescription = typeof(DescriptionAttribute);
            // 获取枚举字段
            FieldInfo[] fields = enumType.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (!field.FieldType.IsEnum)
                    continue;

                // 获取枚举值
                int value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);

                // 不包括空项
                if (value > 0)
                {
                    string text = string.Empty;
                    object[] array = field.GetCustomAttributes(typeDescription, false);

                    if (array.Length > 0) text = ((DescriptionAttribute)array[0]).Description;
                    else text = field.Name; //没有描述，直接取值

                    //添加到列表
                    list.Add(new EnumItem { Value = value, Caption = text });
                }
            }
            return list;
        }
        /// <summary>
        /// 获取指定时间的时间戳，未指定则为当前时间
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static long GetTimestamp(DateTime? d = null)
        {
            DateTime dt = d == null ? DateTime.Now :(DateTime) d;
            TimeSpan ts= dt.ToUniversalTime() - new DateTime(1970, 1, 1);
            return (long) ts.TotalMilliseconds;
        }

        /// <summary>
        /// 随机数，纯数字
        /// </summary>
        /// <returns></returns>
        public static string CreateRandIntCode(int length, int factor)
        {
            string basecode = "0123456789";
            Random random = new Random(factor);
            string re = "";
            for (int i = 0; i < length; i++)
            {
                int number = random.Next(basecode.Length);
                re += basecode.Substring(number, 1);
            }
            return re;
        }

        /// <summary>
        /// 随机数，字符数字组合
        /// </summary>
        /// <param name="length"></param>
        /// <param name="factor"></param>
        /// <returns></returns>
        public static string CreateRandStrCode(int length, int factor)
        {
            string basecode = "123456789abcdefghijklmnprstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
            Random random = new Random(factor);
            string re = "";
            for (int i = 0; i < length; i++)
            {
                int number = random.Next(basecode.Length);
                re += basecode.Substring(number, 1);
            }
            return re;
        }
        /// <summary>
        /// 创建登陆Token
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string CreateToken(int length)
        {
            //定义  
            string basestr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            string sb = "";
            for (int i = 0; i < length; i++)
            {
                int number = random.Next(basestr.Length);
                sb += basestr.Substring(number, 1);
            }
            return sb;
        }
        /// <summary>
        /// 创建编号
        /// </summary>
        /// <returns></returns>
        public static string CreateCode()
        {
            Random rdom = new Random();
            int rnum = rdom.Next();
            var rdstr = CreateRandStrCode(5, rnum);
            var tmsp = GetTimestamp();
            return rdstr.ToUpper() +"_"+ tmsp.ToString();
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="encode">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string EncodeBase64(System.Text.Encoding encode, string source)
        {
            byte[] bytes = encode.GetBytes(source);
            string  enCode= "";
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] output = md5.ComputeHash(bytes);
                enCode = Convert.ToBase64String(output);
            }
            catch
            {
                enCode = source;
            }
            return enCode;
        }

        /// <summary>
        /// 除去Html，关键词查找
        /// </summary>
        /// <param name="contents"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool CheckKeyWord(string contents, string key)
        {
            var hasKey = false;
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<[^>]+>|</[^>]+>");
            contents = regex.Replace(contents, "");
            if (contents.Contains(key))
            {
                hasKey=true;
            }
            return hasKey;
        }

        /// <summary>
        /// 对象转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T CopyTo<T>(this object obj, T target)
        {
            if (obj == null)
            {
                return target;
            }
            var tpts = typeof(T).GetProperties();
            var spts = obj.GetType().GetProperties();
            var pnames = spts.Select(s => s.Name);
            foreach (var sp in tpts.Where(q => pnames.Contains(q.Name)))
            {
                var tpt = spts.FirstOrDefault(q => q.Name == sp.Name);
                sp.SetValue(target, tpt.GetValue(obj));
            }
            return target;
        }
        /// <summary>
        /// 对象转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T MAPTO<T>(this object obj)
        {
            if (obj == null)
            {
                return default(T);
            }
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap(obj.GetType(), typeof(T)));
            var mapper = config.CreateMapper();
            return mapper.Map<T>(obj);
        }
        /// <summary>
        /// 集合转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<T> MAPTO<T>(this IEnumerable list)
        {
            if (list == null)
            {
                throw new ArgumentNullException();
            }
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap(list.GetType(), typeof(T)));
            var mapper = config.CreateMapper();
            return mapper.Map<List<T>>(list);
        }
    }
} 
